package cn.hpclub.server.service;

import java.util.ArrayList;
import java.util.List;

import com.jfinal.ext.plugin.shiro.ShiroMethod;

import cn.hpclub.server.model.Menu;



public class MenuService {

	/**
	 * 树形菜单
	 * @return
	 * @return List<Menu>
	 *
	 */
    public List<Menu> getMenuTreeByParentID(int parentId){
        String sql = " select * from sys_permission where is_deleted = 0 and parent_id in (?) "
 + " union "
                + " select * from sys_permission where is_deleted = 0 and parent_id in (select id from sys_permission where is_deleted = 0 and parent_id in (?)) "
                + " order by sort asc  ";
        List<Menu> areaList = Menu.dao.find(sql, parentId, parentId);
		List<Menu> nodeList = new ArrayList<Menu>();

		for (Menu node1 : areaList) {
			boolean mark = false;
			for (Menu node2 : areaList) {
				if (node1.getParentId() > 0L && node1.getParentId() == node2.getId()) {
					mark = true;
					if (node2.getChildren() == null)
						node2.setChildren(new ArrayList<Menu>());
                    if(ShiroMethod.hasPermission(node1.getStr("permission"))){
                        node2.getChildren().add(node1);
                    }
					break;
				}
			}
            if(!mark && ShiroMethod.hasPermission(node1.getStr("permission"))){
				nodeList.add(node1);
			}
		}
		return nodeList;
	}

    /**
     * header菜单
     * 
     * @return
     * @return List<Menu>
     *
     */
    public List<Menu> getMenuByLevelID(int level){
        String sql = " select * from sys_permission where is_deleted = 0 and level = ? order by sort asc ";
        List<Menu> areaList = Menu.dao.find(sql, level);
        List<Menu> nodeList = new ArrayList<Menu>();

        for(Menu node : areaList){
            if(ShiroMethod.hasPermission(node.getStr("permission"))){
                // remark字段，用于返回前端TOP菜单css样式的class ID
                String url[] = node.getStr("url").split("/");
                node.set("remark", url[url.length - 1]);

                nodeList.add(node);
            }
        }
        return nodeList;
    }
}
